import {Row, Col, Modal, Table, message, Dropdown, Icon, Button, Menu, Form} from 'antd';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Modal from '../../../_antd1.11.2/Modal';
// import Button from '../../../_antd1.11.2/Button';
// import Icon from '../../../_antd1.11.2/Icon';
// import message from '../../../_antd1.11.2/message'
// import Table from '../../../_antd1.11.2/table';
// import Dropdown from '../../../_antd1.11.2/dropdown';
// import Menu from '../../../_antd1.11.2/menu';
// import Form from '../../../_antd1.11.2/form';
const MenuItem = Menu.Item;
const FormItem = Form.Item;

import WeaTools from '../../wea-tools';
import WeaNewScroll from '../../wea-new-scroll';
import WeaSelect from '../../wea-select';
import WeaBrowser from '../../wea-browser';
import WeaScope from '../../wea-scope';
import WeaAssociativeSearchMult from '../wea-associative-search-mult';

import isEqual from 'lodash/isEqual';

//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	delete: '删除',
  	customColSave: '保存',
  	customColCancel: '取消',
};


class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
    constructor(props) {
        super(props);
        this.state = {
        	mainKey: '',
        	conditions: [],
        	//table
        	columns: [],
        	datas: [],
        	selectedRowKeys: [],
        	pageSize: 10,
        	//select
        	selectDatas: {},
        	//modal
        	visible: false,
        	_visible: false,
        	addDatas: [],
        	addDatasInit: [],
        }
        this.onBrowerChange = this.onBrowerChange.bind(this);
        this.onBrowerClick = this.onBrowerClick.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onClear = this.onClear.bind(this);
        this._onOk = this._onOk.bind(this);
        this._onCancel = this._onCancel.bind(this);
		this.doAdd = this.doAdd.bind(this);
    }
    componentDidMount() {
//  	const datas_mock = [
//		      	{
//		      		sharetype: 1,
//		      		sharetypespan: "人员",
//			        relatedshare: "6084",
//			        relatedsharespan: "韩佳人6",
//			        relatedshareurl: '/',
//		      	},
//			    {
//			    	sharetype: 6,
//			    	sharetypespan: "岗位",
//			        relatedshare: "88",
//			        relatedsharespan: "20140202",
//			        relatedshareurl: "/",
//			        joblevel: "2",
//			        joblevelspan: "总部",
//			        joblevelurl: "/",
//			        jobfield:'5',
//			        jobfieldspan:'下级分部',
//			        jobfieldurl: '/',
//			    },
//	    ];
	    const { datas = [] } = this.props;
    	this.getDates();
      	this.setState({ datas, selectDatas: this.getSelectDatas(datas) });
//  	this.setState({
//  		datas: this.addKeytoDatas(datas_mock),
//  		selectDatas: this.getSelectDatas(this.addKeytoDatas(datas_mock))
//  	});
    }
    componentWillReceiveProps(nextProps){
	    const { datas = [] } = this.props;
    	const nextDatas = nextProps.datas || [];
    	if(!isEqual(datas, nextDatas)){
    		this.setState({
    			datas: this.addKeytoDatas(nextDatas),
    			selectDatas: this.getSelectDatas(this.addKeytoDatas(nextDatas))
    		});
    	}
    }
    render() {
    	const { inputStyle = {}, type = '141', modalStyle = {}, children, contentHeight = 460 } = this.props;
    	const { datas, selectDatas, visible, _visible, selectedRowKeys } = this.state;
        const buttons = [
            <Button key="submit" type="primary" size="large" onClick={this.onOk} disabled={false}>确 定</Button>,
            <Button key="clear" type="ghost" size="large" onClick={this.onClear}>清 除</Button>,
            <Button key="back" type="ghost" size="large" onClick={this.onCancel}>取 消</Button>
       	];
       	const _buttons = [
            <Button key="submit" type="primary" size="large" onClick={this._onOk} >保 存</Button>,
            <Button key="back" type="ghost" size="large" onClick={this._onCancel}>取 消</Button>
       	];
        return (
          	<div className='wea-hrm-condition'>
	          	{
	          		children ? <div style={{display: 'inline-block',cursor: 'pointer'}} onClick={this.onBrowerClick} >{children}</div> :
	            	<WeaAssociativeSearchMult
		                {...this.props}
		                style={ inputStyle }
		                datas={ selectDatas }
		                selectedValues={this.getSelectKeys()}
		                isClearData={JSON.stringify(selectDatas) === '{}'}
		                type={type}
		                clickCallback={this.onBrowerClick}
		                onChange={this.onBrowerChange}
		            />
	          	}
            	<Modal wrapClassName="wea-hr-muti-input"
		            title={this.getTitle()}
		            width={modalStyle.width}
		            maskClosable={false}
		            visible={visible}
		            onCancel={this.onCancel}
		            footer={buttons}
		        >
		            <div className='wea-table-edit wea-hrm-condition-table' style={{height: contentHeight }}>
		            	<Row className="wea-table-edit-title" >
							<Col>
								{ '已添加条件' }
								<Button type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete.bind(this,selectedRowKeys)} ><Icon type="minus" /></Button>
								<Button type="primary"  title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
							</Col>
			            </Row>
                        <WeaNewScroll height={contentHeight - 45}>
                            <Table
			                	columns={this.getColumns()}
			                	dataSource={datas}
			                	pagination={this.getPagination()}
			                	rowSelection={this.getRowSelection()}
			                />
                        </WeaNewScroll >
		            </div>
		            <Modal wrapClassName="wea-hr-muti-input"
			            title={this.getTitle(true)}
			            width={modalStyle.width * 0.6}
			            maskClosable={false}
			            visible={_visible}
			            onCancel={this._onCancel}
			            footer={_buttons}
			        >
			            {this.getAddComponent()}
		            </Modal>
	            </Modal>
          	</div>
        );
    }
    //添加条件
    doAddComponentChange(type, key, value, list, url){
    	const { addDatas, conditions, mainKey } = this.state;
    	let _addDatas = [].concat(addDatas);
    	if(value){
	    	if(type === 'BROWSER') {
	    		let ids = value.split(',');
	    		let addData = {..._addDatas[0]};
	    		_addDatas = [];
	    		ids.map((id,i) => {
	    			let _addData = {...addData};
	    			_addData[key] = id;
	    			_addData[key + 'span'] = list[i]['name'] || list[i]['lastname'];
	    			_addData[key + 'url'] = `${url}${id}`;
	    			_addDatas.push(_addData);
	    		});
	    	}
		    if(type === 'SELECT') {
		    	const init = key === mainKey;
	    		_addDatas = _addDatas.map(addData => {
	    			let _addData = init ? {} : {...addData};
	    			let hasSec = false;
	    			init && conditions[1][value].map(condition => {
	    				if(condition.conditionType === 'INPUT_INTERVAL' && condition.domkey[0] === 'seclevel')
	    					hasSec = true;
	    				if(condition.conditionType === 'SELECT')
		    				condition.options.map(o => {
		    					if(o.selected === true){
		    						_addData[condition.domkey[0]] = o.key;
		    						_addData[condition.domkey[0] + 'span'] = o.showname;
		    					}
		    				});
	    			});
	    			if(hasSec) _addData.seclevel = '0-100';
	    			list.map(l => {
	    				if(l.key === value){
	    					_addData[key] = value;
	    					_addData[key + 'span'] = l.showname;
	    					if(url)	_addData[key + 'url'] = `${url}${value}`;
	    				}
	    			})
	    			return _addData
	    		})
		    }
		    if(type === 'INPUT_INTERVAL'){
		    	_addDatas = _addDatas.map(addData => {
		    		let _addData = {...addData};
					_addData[key] = `${value}-${list}`;
					//_addData[key + 'span'] = url;
		    		return _addData
		    	})
		    }
    	}
	    this.setState({addDatas:_addDatas})
    }
    getAddComponent(){
    	const { conditions, addDatas, mainKey } = this.state;
    	if(!`${conditions}`) return null;
    	const index = addDatas[0][mainKey];
    	return (
    		<div style={{ padding: 20 }}>
    			<FormItem
                    label={conditions[0].label}
                    labelCol={{span: conditions[0].labelcol}}
                    wrapperCol={{span: conditions[0].fieldcol}}>
                        <WeaSelect
                        	value={index}
    						onChange={v => this.doAddComponentChange('SELECT',conditions[0].domkey[0],v,conditions[0].options)}
		                    options= {conditions[0].options}
		                />
                </FormItem>
				{
					conditions[1][index].map(condition => {
						let showDropMenu = false;
						let replaceDatas = [];
						let startValue = 0;
						let endValue = 100;
						if(condition.conditionType === 'BROWSER') {
							if(condition.browserConditionParam)
								showDropMenu = condition.browserConditionParam.type=='4' || condition.browserConditionParam.type=='164';//部门分部显示维度菜单
							addDatas.map(addData => {
								addData[condition.domkey[0]] && replaceDatas.push({
									id:addData[condition.domkey[0]] || '',
									name: addData[`${condition.domkey[0]}span`] || '',
								})
							});
						}
						if(condition.conditionType === 'INPUT_INTERVAL' && addDatas[0][condition.domkey[0]]){
							const value = addDatas[0][condition.domkey[0]].split('-');
							startValue = Number(value[0]);
							endValue = Number(value[1]);
						}
						return (
							<FormItem
			                    label={condition.label}
			                    labelCol={{span: condition.labelcol}}
			                    wrapperCol={{span: condition.fieldcol}}>
			    					{
			    						condition.conditionType === 'SELECT' &&
				    					<WeaSelect
				    						value={addDatas[0][condition.domkey[0]] || '1'}
				    						onChange={v => this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options)}
						                    options= {condition.options}
						                />
			    					}
			    					{
			    						condition.conditionType === 'BROWSER' &&
			    						<WeaBrowser {...condition.browserConditionParam}
			    							replaceDatas={replaceDatas}
			    							showDropMenu={showDropMenu}
			    							onChange={(v, name, list) => this.doAddComponentChange('BROWSER',condition.domkey[0],v,list,condition.browserConditionParam.linkUrl)}
			    						/>

			    					}
			    					{
			    						condition.conditionType === 'INPUT_INTERVAL' &&
			    						<WeaScope
			    							min={[0,100]}
			    							max={[0,100]}
			    							domkey={condition.domkey}
			    							startValue={startValue}
			    							endValue={endValue}
			    							onChange={(start, end) => this.doAddComponentChange('INPUT_INTERVAL',condition.domkey[0],start,end)}
			    						/>
			    					}
			                </FormItem>
						)
					})
				}
			</div>
    	)
    }
    //util
    getDates(){
		let { conditionURL = '' } = this.props;
    	WeaTools.callApi(conditionURL).then(datas => {
    		const { conditions, columns } = datas;
    		const mainKey = columns[0].dataIndex;
    		let key = '', showname = '';
    		conditions[0].options.map(o => {
    			if(o.selected){
    				key = o.key;
    				showname = o.showname;
    			}
    		})
    		if(!key){
    			key = conditions[0].options[0].key;
    			showname = conditions[0].options[0].showname;
    		}
    		let addDatas = mainKey ? [{ [mainKey]: key, [`${mainKey}span`]: showname }] : [];
    		this.setState({ mainKey, conditions, columns, addDatas, addDatasInit: addDatas });
    	})
    }
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    getSelectDatas(datas){
    	let selectDatas = {};
    	datas.map(data => {
    		const { key } = data;
    		let name = null;
    		for(let k in data){
    			if(k !== 'key'){
    				if(`${k}span` in data){
    					name += (' / ' + data[`${k}span`]);
    				}else{
    					name += (' / ' + data[k]);
    				}
    			}
    		}
    		selectDatas[key] = {
    			id: key,
    			name: (
    				<span>
    					{name}
    				</span>
    			)
    		}
    	});
    	return selectDatas;
    }
    //select
    getSelectKeys(){
    	const { selectDatas } = this.state;
    	let selectKeys = [];
    	for(key in selectDatas){
    		selectKeys.push(key);
    	}
    	return selectKeys
    }
    onBrowerClick(){
    	this.setState({visible: true})
    }
    onBrowerChange(values, selectDatas){
    	this.setState({selectDatas})
    }
    //table
    getColumns(){
    	const { columns, datas } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return (record[`${_col.dataIndex}span`] || record[_col.dataIndex])
			}
			return _col
		});
		const locale = this.getLocale();
		_columns.push({
			title: '',
			dataIndex: 'ops',
			key: 'ops',
			width: 80,
            className:"wea-table-operates",
            render: ( text, record, index )=> {
            	const menu = (
            		<Menu>
                        <MenuItem>
	                        <a href='javascript:void(0);' onClick={this.doDelete.bind(this,[record.key])}>{locale.delete}</a>
	                    </MenuItem>
                    </Menu>
            	)
            	return (
                    <div className='wea-hrm-condition-table-ops'>
                        <Dropdown overlay={menu}>
                            <span>
                                {locale.operates} <Icon type="caret-down" />
                            </span>
                        </Dropdown>
                    </div>
                )
            }
		});
		return _columns
    }
    getPagination() {
		return false
	}
    getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
			}
		}
		return rowSelection
	}
    //btns
    doAdd(){
    	this.setState({_visible: true})
    }
    doDelete(keys){
    	const { datas } = this.state;
    	let _datas = [].concat(datas);
    	keys.map(key => {
    		_datas = _datas.filter(_data => _data.key !== key)
    	});
    	_datas = this.addKeytoDatas(_datas);
    	this.setState({
    		datas: _datas,
    		selectedRowKeys: [],
    		selectDatas: this.getSelectDatas(_datas),
    	});
    }
    //modal
    getTitle(bool){
    	const { icon = '', title = '', iconBgcolor = ''} = this.props;
    	return (
    		<Row>
                <Col span="8" style={{ paddingLeft:20, lineHeight:'48px' }}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{ bool ? '添加条件' : title}</span>
                    </div>
                </Col>
            </Row>
    	)
    }
    onOk(){
    	const { datas } = this.state;
    	this.setState({visible: false});
    	if(typeof this.props.onChange === 'function'){
	    	let _datas = datas.map((data, i) => {
				let _data = {...data}
				delete _data.key
				return _data
			});
	    	this.props.onChange('', '', _datas);
    	}
    }
    onClear(){
    	this.setState({
    		selectDatas: {},
    		datas: [],
    		selectedRowKeys: []
    	})
    }
    onCancel(){
    	const { datas = [] } = this.props;
    	this.setState({
    		datas,
    		selectDatas: this.getSelectDatas(datas),
    		selectedRowKeys: [],
    		visible: false,
    	})
    }
    _onOk(){
    	const { datas, addDatas, addDatasInit } = this.state;
    	let _datas = [].concat(datas);
    	let _addDatas = [].concat(addDatas);
    	_addDatas = _addDatas.map((addData, i)=> {
    		let _addData = {...addData};
    		_addData.key = datas.length + i;
    		return _addData
    	})
    	if(_addDatas.length > 0){
    		_datas = _datas.concat(_addDatas)
    		this.setState({
    			_visible: false,
    			datas: _datas,
    			selectDatas: this.getSelectDatas(_datas),
    			addDatas: addDatasInit,
    		})
    	}else{
    		message.warning('数据不能为空！',500);
    	}
    }
    _onCancel(){
    	const { addDatasInit } = this.state;
    	this.setState({_visible: false, addDatas: addDatasInit})
    }
}

export default Main;